<?php

namespace app\admin\controller;

use app\helpers\Common;
use app\common\model\AdminMenu;

use think\facade\Db;
use think\Request;

class AdminRole extends Base
{
    protected function initialize()
    {
        parent::initialize();

        // 当前model
        $this->model = 'AdminRole'; // Ajax请求有效

        $this->indexView = 'adminrole:list';
        $this->addView = 'adminrole:add';
        $this->editView = 'adminrole:edit';

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere[] = ['status', '<>', config('constants.SOFT_DELETE_STATUS')];
        $this->defaultWhere = $defaultWhere;
    }

    /**
     * List
     */
    public function index(Request $request)
    {
        return parent::index($request);
    }

    /**
     * Add
     */
    public function roleAdd(Request $request)
    {
        return parent::add($request);
    }

    /**
     * Add Post
     */
    public function roleAddPost(Request $request, $redirect = '')
    {
        return $this->savePost($request);
    }

    /**
     * Edit
     */
    public function roleEdit(Request $request, $id, $redirect = '')
    {
        return parent::edit($request, $id);
    }

    /**
     * Edit Post
     */
    public function roleEditPost(Request $request, $id, $redirect = '')
    {
        return $this->savePost($request);
    }

    /**
     * Save Post
     */
    protected function savePost($request, $id = '', $redirect = '')
    {
        return parent::savePost($request, $id, $redirect);
    }

    /**
     * Delete
     */
    public function roleDelete(Request $request, $id)
    {
        return parent::roleDelete($request, $id);
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        if ($request->isPost()) {
            $data = $request->param();

            $result = $model->where('id', $data['id'])->update($data);
            if ($result === false) {
                return $this->error('操作失败!', url('admin/' . $this->model . '/index'));
            }

            return $this->success('操作成功！', (string)url('admin/' . $this->model . '/index'));
        } else {
            return $this->error('请求方式错误!');
        }
    }

    /**
     * 权限
     */
    public function getMenus(Request $request)
    {
        $param = request()->param();
        //$model = new AdminMenu();

        $access = [];
        if (isset($param['id'])) {
            $roleId = $param['id'];
            //$access = Db::name('admin_auth_access')->where('role_id', $roleId)->column('id');
            $access = Db::name('admin_roles')->where('id', $roleId)->value('access');
            $access = explode(',', $access);
        }

        $list = [];
        $recursive = function ($parentId) use (&$recursive, &$list, $access) {
            $where = [
                ['parent_id', '=', $parentId],
                ['status', '=', 1]
            ];
            $field = 'id, name as title, parent_id';
            $menus = Db::name('admin_menu')->where($where)->field($field)->order('sorting', 'ASC')->select()->toArray();
            foreach ($menus as $key => &$menu) {
                //$menu['spread'] = true; // 节点是否初始展开
                $menu['field'] = 'access[]';
                if (in_array($menu['id'], $access)) {
                    $menu['checked'] = true;
                }

                // 下级菜单
                $menu['children'] = $recursive($menu['id']);
                if ($parentId == 0) {
                    $list[] = $menu;
                }
            }

            return $menus;
        };

        $recursive(0);

        return json($list);
    }

    /**
     * 检查名称是否已存在
     *
     * @return \think\response\Json
     */
    public function checkName(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        $name = $request->param('name');
        $where = [
            ['name', '=', $name],
            ['status', '=', 1]
        ];
        $info = $model->where($where)->field('id')->find();

        if ($info) {
            return json(['code' => 1]);
        } else {
            return json(['code' => 0]);
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->param();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }

        return $where;
    }
}